package com.hhd.flow.engine.cmd.impl;

import com.hhd.flow.engine.utils.CommonUtils;
import com.hhd.flow.engine.utils.FlowUtils;
import com.hhd.flow.engine.vo.CommentType;
import com.hhd.flow.engine.vo.FlowModel;
import com.hhd.flow.engine.vo.UserTask;
import com.hhd.flow.entity.FlowComment;
import com.hhd.flow.entity.FlowProcessInstance;
import com.hhd.flow.entity.FlowUserTask;
import com.hhd.flow.exception.FlowException;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.SuperBuilder;

@Setter
@Getter
@SuperBuilder(toBuilder = true)
public class SubtractUserSignCommand extends BaseCommand<Void> {
    private String flowUserTaskId;
    private String userTaskId;

    //下面是运行时的参数
    private FlowUserTask flowUserTask;
    private FlowModel flowModel;
    private UserTask currentUserTaskNode;
    private UserTask subtractingUserTask;

    @Override
    public Void execute() {
        prepare();

        doSubtractUserSign();

        createComment();

        return null;
    }

    private void createComment() {
        FlowComment flowComment = FlowUtils.createComment(flowUserTask, createCommentMessage(), null, null, CommentType.subtractUserSign, null);
        flowComment.setCommentInfo(subtractingUserTask.getTaskName());
        getEngine().getFlowCommentService().save(flowComment);
    }

    public String createCommentMessage() {
        return null;
    }

    private void doSubtractUserSign() {
        flowModel = flowModel.removeNodeById(userTaskId);

        getEngine().getFlowProcessInstanceService().lambdaUpdate()
                .set(FlowProcessInstance::getModel, flowModel.getModelString())
                .eq(FlowProcessInstance::getId, flowUserTask.getProcessInstanceId())
                .update();
    }

    private void prepare() {
        flowUserTask = getEngine().getFlowUserTaskService().getById(flowUserTaskId);
        CommonUtils.isEmptyThrow(flowUserTask, new FlowException("没有找到用户任务：" + flowUserTaskId));
        if (flowUserTask.getNotify()) {
            throw new FlowException("知会任务不支持加签的操作");
        }

        flowModel = loadFlowModelByProcessInstanceId(flowUserTask.getProcessInstanceId());
        currentUserTaskNode = flowModel.getUserTaskById(flowUserTask.getTaskDefinitionId());
        subtractingUserTask = flowModel.getUserTaskById(userTaskId);
    }
}
